package LeetCode;

public class Test1 {
    public int[] searchRange(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1;
        int[] ret = {-1,-1};
        // 边界判断
        if(n == 0) return ret;
        // 找左端点
        while(left < right) {
            int mid = left + ((right - left) >> 1);
            if(nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        // 如果数组中找不到 target 直接返回
        if(nums[left] != target) return ret;
        ret[0] = left;

        // 找右端点
        // 注意找完一个端点后，left 或 right 指针要归位
        // 左端点找完 left 就不用动了
        right = n - 1;
        while(left < right) {
            int mid = left + ((right - left + 1) >> 1);
            if(nums[mid] <= target) {
                left = mid;
            }else {
                right = mid - 1;
            }
        }
        ret[1] = left;
        return ret;
    }

    public int mySqrt(int x) {
        if(x < 1) return 0;

        long left = 1, right = x;
        while(left < right) {
            long mid = left + ((right - left + 1) >> 1);
            long target = mid * mid;
            if(target <= x) {
                left = mid;
            }else {
                right = mid - 1;
            }
        }
        return (int)left;
    }

    public int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        // 边界判定
        if(nums[right] < target) return right + 1;
        while(left < right) {
            int mid = left + ((right - left) >> 1);
            if(nums[mid] < target) {
                left = mid + 1;
            }else {
                right = mid;
            }
        }

        return left;
    }

    public int peakIndexInMountainArray(int[] arr) {
        int left = 0, right = arr.length - 1;
        while(left < right) {
            int mid = left + ((right - left + 1) >> 1);
            if(arr[mid - 1] < arr[mid]) {
                left = mid;
            }else {
                right = mid - 1;
            }
        }
        return left;
    }
}
